<template>
  <div class="layout-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <span>潍坊理工小助手</span>
      </div>
      <div class="user-wrapper">
        <!-- 未登录状态 -->
        <el-button v-if="!isLoggedIn" type="primary" @click="showLoginModal">
          登录
        </el-button>

        <!-- 已登录状态 -->
        <el-dropdown v-else @command="handleCommand">
          <span class="user-dropdown">
            <el-avatar :size="32" icon="UserFilled" />
            <span class="username">{{ userStore.userInfo.userName }}</span>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 个人信息弹窗 -->
    <el-dialog
      v-model="showUserInfo"
      title="个人信息"
      width="400px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-descriptions :column="1" border>
        <!-- <el-descriptions-item label="用户名">{{ userStore.userInfo.userName }}</el-descriptions-item> -->
        <el-descriptions-item label="姓名">{{ userStore.userInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ userStore.userInfo.sex }}</el-descriptions-item>
        <el-descriptions-item label="学号">{{ userStore.userInfo.studentNumber }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ userStore.userInfo.phonenumber }}</el-descriptions-item>
        <el-descriptions-item label="专业">{{ userStore.userInfo.major }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{ userStore.userInfo.classroom }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 登录弹窗 -->
    <el-dialog
      v-model="loginVisible"
      width="460px"
      :close-on-click-modal="false"
      :show-close="true"
      destroy-on-close
      class="login-dialog"
    >
      <login-modal
        v-model="loginVisible"
        @login-success="handleLoginSuccess"
        @switch-to-register="switchToRegister"
      />
    </el-dialog>

    <div class="main-content">
      <!-- 侧边栏 -->
      <aside class="sidebar" :class="{ 'collapsed': isSidebarCollapsed }">
        <div class="sidebar-header">
          <el-button class="new-chat-btn" @click="clearChat" type="primary">
            <el-icon><Plus /></el-icon>
            <span v-show="!isSidebarCollapsed">新对话</span>
          </el-button>
          <el-button 
            class="collapse-btn" 
            @click="toggleSidebar" 
            :icon="isSidebarCollapsed ? ArrowRight : ArrowLeft"
          />
        </div>

        <!-- 菜单项 -->
        <div class="menu-items">
          <router-link to="/chat" class="menu-item" active-class="active">
            <el-icon><ChatLineRound /></el-icon>
            <span v-show="!isSidebarCollapsed">聊天</span>
          </router-link>

          <!-- 历史对话折叠面板 -->
          <div class="history-section">
            <div class="history-header" @click="toggleHistory">
              <el-icon><Document /></el-icon>
              <span v-show="!isSidebarCollapsed">历史对话</span>
              <!-- <el-icon class="expand-icon" :class="{ 'is-active': isHistoryExpanded }">
                <ArrowDown />
              </el-icon> -->
            </div>
            
            <!-- 历史对话列表 -->
            <div class="history-list" v-show="isHistoryExpanded">
              <div 
                v-for="chat in chatStore.processedHistory" 
                :key="chat.chatId" 
                class="history-item"
                :class="{ 'active': chat.chatId === chatStore.currentChatId }"
                @click="switchChat(chat)"
              >
                <el-icon><ChatDotRound /></el-icon>
                <span class="history-title">{{ chat.title }}</span>
              </div>
            </div>
          </div>
        </div>
      </aside>

      <!-- 主要内容区域 -->
      <main class="content" :class="{ 'content-expanded': isSidebarCollapsed }">
        <router-view #default="{ Component }">
          <keep-alive>
            <component :is="Component" ref="currentComponent" />
          </keep-alive>
        </router-view>
      </main>
    </div>
  </div>
</template>
<script setup>
import {  ref, onMounted, nextTick, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, ArrowRight, ArrowLeft, ChatLineRound, Calendar, Document, ArrowDown, ChatDotRound } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import LoginModal from './auth/LoginModal.vue'
import { useChatStore } from '@/stores/chat'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const chatStore = useChatStore()
const isSidebarCollapsed = ref(false)
const currentComponent = ref(null)
const loginVisible = ref(false)
const isLoggedIn = computed(() => {
  return !!userStore.token
})

const showUserInfo = ref(false)

// 添加历史对话相关的数据
const chatHistory = ref([])

// 添加历史对话展开状态
const isHistoryExpanded = ref(false)

// 格式化时间的函数
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 从localStorage加载侧边栏状态
onMounted(() => {
  const savedState = localStorage.getItem('sidebarState')
  if (savedState) {
    isSidebarCollapsed.value = JSON.parse(savedState)
  }
  
  // 获取历史对话列表
  if (userStore.token) {
    chatStore.fetchHistoryList()
  }
})

// 切换侧边栏
const toggleSidebar = () => {
  isSidebarCollapsed.value = !isSidebarCollapsed.value
  localStorage.setItem('sidebarState', JSON.stringify(isSidebarCollapsed.value))
  window.dispatchEvent(new Event('resize'))
}

// 清除聊天
const clearChat = async () => {
  // 先切换到聊天页面
  if (route.path !== '/chat') {
    await router.push('/chat')
  }
  // 等待组件挂载完成
  nextTick(() => {
    const chatComponent = currentComponent.value
    if (chatComponent?.resetChat) {
      chatComponent.resetChat()
      ElMessage.success('已开启新对话')
    }
  })
}
// 显示登录弹窗
const showLoginModal = () => {
  loginVisible.value = true
}

// 处理登录成功
const handleLoginSuccess = async () => {
  loginVisible.value = false
  ElMessage.success('登录成功')
  
  // 确保在聊天页面
  if (route.path !== '/chat') {
    await router.push('/chat')
  }
  
  // 使用 setTimeout 确保组件完全挂载
  setTimeout(() => {
    const chatComponent = currentComponent.value
    if (chatComponent?.resetChat) {
      chatComponent.resetChat()
      ElMessage.success('已开启新对话')
    }
  }, 100)
}

// 监听登录状态变化
watch(() => userStore.token, (newToken) => {
  if (newToken) {
    // 登录后获取历史对话
    chatStore.fetchHistoryList()
  } else {
    // 退出登录时清空历史对话
    chatStore.clearHistory()
  }
}, { immediate: true })

// 修改 handleCommand 方法
const handleCommand = (command) => {
  if (command === 'profile') {
    showUserInfo.value = true
  } else if (command === 'logout') {
    userStore.removeToken()
    chatStore.clearHistory() // 确保清空历史对话
    ElMessage.success('退出成功')
    router.push('/')
  }
}

// 切换历史对话展开状态
const toggleHistory = () => {
  isHistoryExpanded.value = !isHistoryExpanded.value
}

// 切换对话
const switchChat = async (chat) => {
  chatStore.setCurrentChatId(chat.chatId)
  // 切换到聊天页面
  if (route.path !== '/chat') {
    await router.push('/chat')
  }
  // 通知聊天组件加载历史消息
  nextTick(() => {
    const chatComponent = currentComponent.value
    if (chatComponent?.loadHistoryMessages) {
      chatComponent.loadHistoryMessages(chat.messages)
    }
  })
}
</script>

<style scoped>
.layout-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  height: 60px;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.user-wrapper {
  display: flex;
  align-items: center;
}

.profile-information{
  z-index: 1;
  height: 300px;
  width: 300px;
  padding: 10px;
  font-size: 18px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  /* border: #333 solid 1px; */
  position: absolute;
  right: 120px;
  top: 30px;
}

.profile-information td{
  padding: 10px;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin-left: 8px;
  color: #333;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  position: relative;
}

.sidebar {
  position: fixed;
  height: calc(100vh - 60px);
  width: 240px;
  background-color: #f5f7f9;
  border-right: 1px solid #e6e6e6;
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  z-index: 100;
}

.sidebar.collapsed {
  width: 64px;
}

.sidebar-header {
  padding: 16px;
  display: flex;
  gap: 8px;
}

.new-chat-btn {
  flex: 1;
}

.collapse-btn {
  padding: 8px;
}

.menu-items {
  padding: 8px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  color: #666;
  text-decoration: none;
  border-radius: 6px;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #e6e6e6;
}

.menu-item.active {
  background-color: #ecf5ff;
  color: #409eff;
}

.content {
  flex: 1;
  overflow: auto;
  padding: 20px;
  background-color: #fff;
  margin-left: 240px;
  transition: all 0.3s;
  min-height: calc(100vh - 60px);
}

.content-expanded {
  margin-left: 64px;
}

:deep(.login-dialog) {
  border-radius: 8px;
}

:deep(.login-dialog .el-dialog__header) {
  margin: 0;
  padding: 20px 30px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.login-dialog .el-dialog__body) {
  padding: 0;
}

:deep(.login-dialog .el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
}

.history-section {
  margin-top: 8px;
}

.history-header {
  display: flex;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  border-radius: 6px;
  transition: background-color 0.2s;
  gap: 8px;
}

.history-header:hover {
  background-color: #e6e6e6;
}

.expand-icon {
  margin-left: auto;
  transition: transform 0.3s;
}

.expand-icon.is-active {
  transform: rotate(180deg);
}

.history-list {
  margin-top: 4px;
  padding-left: 12px;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin: 4px 0;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
  gap: 8px;
  font-size: 14px;
  color: #666;
}

.history-item:hover {
  background-color: #e6e6e6;
}

.history-item.active {
  background-color: #ecf5ff;
  color: #409eff;
}

.history-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.sidebar.collapsed .history-item {
  padding: 8px;
  justify-content: center;
}

.sidebar.collapsed .history-title {
  display: none;
}

.bottom-menu {
  padding: 16px;
  border-top: 1px solid #e0e0e0;
}

/* 折叠状态下的历史对话样式 */
.sidebar.collapsed .history-header {
  padding: 12px 8px;
  justify-content: center;
}

.sidebar.collapsed .history-list {
  padding-left: 0;
}

.sidebar.collapsed .history-item {
  padding: 8px;
  justify-content: center;
}

.sidebar.collapsed .history-title,
.sidebar.collapsed .history-header span {
  display: none;
}

/* 保持图标居中显示 */
.sidebar.collapsed .el-icon {
  margin: 0;
}
</style>
